package reduce.fz.com.reduce.util.base;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.support.multidex.MultiDexApplication;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.sdk.android.AlibabaSDK;
import com.alibaba.sdk.android.callback.InitResultCallback;
import com.duanqu.qupai.engine.session.VideoSessionCreateInfo;
import com.duanqu.qupai.sdk.android.QupaiService;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.entity.UMessage;


import java.util.Stack;

import cn.sharesdk.framework.ShareSDK;
import de.greenrobot.event.EventBus;
import io.vov.vitamio.Vitamio;
import reduce.fz.com.reduce.bean.MessageNotice;
import reduce.fz.com.reduce.util.HttpUtils;
import reduce.fz.com.reduce.util.ReduceLog;
import reduce.fz.com.reduce.util.ScreenUtils;

/**
 * FeelApp
 * 提供Activity的管理，避免推出应用造成关闭不了某些隐藏的activity造成的问题
 *
 * @author lipf
 */
public class ReduceApplication extends MultiDexApplication {

    private static Stack<Activity> activityStack;
    private static ReduceApplication mInstance;
    private QupaiService qupaiService;
    private PushAgent mPushAgent;


    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        ScreenUtils.initScreen(this);
        FileCache.init(this);
        HttpUtils.init(this);
        Boolean a = Vitamio.isInitialized(this);
        //初始化第三方sdk
        initSDK();
        //初始化
        initQupaiSDK();
        //初始化友盟push
        resetUMengPushHandle();
    }

    public void initSDK() {
        SMSManager.init(this);
    }

    public void initShareSDK() {
        ShareSDK.initSDK(this);
    }


    public void initQupaiService() {
        qupaiService = AlibabaSDK.getService(QupaiService.class);
        VideoSessionCreateInfo info = new VideoSessionCreateInfo.Builder()
                .setOutputDurationLimit(Contant.DEFAULT_DURATION_LIMIT)
                .setOutputVideoBitrate(Contant.DEFAULT_BITRATE)
                .setHasImporter(true)
                .setWaterMarkPath(Contant.WATER_MARK_PATH)
                .setWaterMarkPosition(1)
                .setHasEditorPage(true)
                .build();
        qupaiService.initRecord(info);
        if (qupaiService != null) {
            qupaiService.addMusic(0, "Athena", "assets://Qupai/music/Athena");
            qupaiService.addMusic(1, "Box Clever", "assets://Qupai/music/Box Clever");
            qupaiService.addMusic(2, "Byebye love", "assets://Qupai/music/Byebye love");
            qupaiService.addMusic(3, "chuangfeng", "assets://Qupai/music/chuangfeng");
            qupaiService.addMusic(4, "Early days", "assets://Qupai/music/Early days");
            qupaiService.addMusic(5, "Faraway", "assets://Qupai/music/Faraway");
        }
    }

    public QupaiService getQupaiService() {
        return qupaiService;
    }


    public void initQupaiSDK() {
        AlibabaSDK.asyncInit(this, new InitResultCallback() {
            @Override
            public void onSuccess() {
                Toast.makeText(ReduceApplication.this, "初始化成功 ", Toast.LENGTH_SHORT)
                        .show();
                initQupaiService();

            }

            @Override
            public void onFailure(int i, String s) {
                Toast.makeText(ReduceApplication.this, "初始化失败 " + s, Toast.LENGTH_SHORT)
                        .show();
            }
        });
    }

    public void resetUMengPushHandle() {

        mPushAgent = PushAgent.getInstance(this);
        mPushAgent.setDebugMode(true);
        UmengMessageHandler messageHandler = new UmengMessageHandler() {
            @Override
            public void dealWithCustomMessage(final Context context, final UMessage msg) {
                new Handler().post(new Runnable() {

                    @Override
                    public void run() {
                        boolean isClickOrDismissed = true;
                        if (isClickOrDismissed) {
                        } else {
                        }
                        MessageNotice notice = JSON.parseObject(msg.custom, MessageNotice.class);
                        EventBus.getDefault().post(notice);
                    }
                });
            }
        };
        mPushAgent.setMessageHandler(messageHandler);
    }


    /**
     * 初始化
     */

    public void initSMSSDK() {
    }

    public static ReduceApplication getInstance() {
        return mInstance;
    }

    /**
     * 获取activity堆栈大小
     */
    public int getActivityStackSize() {
        if (activityStack == null) {
            activityStack = new Stack<Activity>();
        }
        return activityStack.size();
    }

    /**
     * add Activity 添加Activity到栈
     */
    public void addActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<Activity>();
        }
        activityStack.add(activity);
    }

    /**
     * get current Activity 获取当前Activity（栈中最后一个压入的）
     */
    public Activity currentActivity() {
        if (activityStack == null || activityStack.isEmpty()) {
            return null;
        }
        Activity activity = activityStack.lastElement();
        return activity;
    }

    /**
     * 栈 中是否有 Activity
     */
    public boolean hasActivity(Class<?> cls) {
        if (cls == null || activityStack == null || activityStack.isEmpty()) {
            return false;
        }
        for (Activity activity1 : activityStack) {
            if (cls.equals(activity1.getClass())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 结束当前Activity（栈中最后一个压入的）
     */
    public void finishActivity() {
        if (activityStack == null || activityStack.isEmpty()) {
            return;
        }
        Activity activity = activityStack.lastElement();
        finishActivity(activity);
    }

    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            if (activityStack != null) {
                activityStack.remove(activity);
            }
            if (!activity.isFinishing()) {
                activity.finish();
            }
            activity = null;
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(Class<?> cls) {
        if (activityStack != null) {
            for (int i = activityStack.size() - 1; i >= 0; i--) {
                Activity activity = activityStack.get(i);
                if (activity.getClass().equals(cls)) {
                    finishActivity(activity);
                }
            }
        }
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        if (activityStack != null) {
            for (int i = 0, size = activityStack.size(); i < size; i++) {
                if (null != activityStack.get(i)) {
                    try {
                        Activity activity = activityStack.get(i);
                        if (!activity.isFinishing()) {
                            activity.finish();
                        }
                    } catch (Exception e) {
                        ReduceLog.e(e);
                    }
                }
            }
            activityStack.clear();
        }
    }

    @Override
    public void onTerminate() {
        try {
            exitApp();
            super.onTerminate();
        } catch (Exception e) {
            ReduceLog.e(e);
        }
    }

    /**
     * 退出应用程序
     */
    public void exitApp() {
        try {
            finishAllActivity();
        } catch (Throwable e) {
        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
    }
}
